package com.babble.blog.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 缓存配置类
 *
 * @author wm
 */
@Configuration
public class RedisConfig {
	@Bean
	public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		redisTemplate.setKeySerializer(keySerializer());
		redisTemplate.setValueSerializer(valueSerializer());
		redisTemplate.setHashKeySerializer(keySerializer());
		redisTemplate.setHashValueSerializer(valueSerializer());
		redisTemplate.setEnableTransactionSupport(true);
		return redisTemplate;
	}

	// 创建redis的key序列化规则
	private RedisSerializer<?> keySerializer() {
		return new StringRedisSerializer();
	}

	// 值使用jackson进行序列化
	private RedisSerializer<?> valueSerializer() {
		return new GenericFastJsonRedisSerializer();
	}
}
